//---------------------------------------------------------------------
// File: RegExValidationStep.cs
// 
// Summary: 
//
//---------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
// PURPOSE.
//---------------------------------------------------------------------

namespace Microsoft.Services.BizTalkApplicationFramework.BizUnit
{
	using System;
	using System.IO;
	using System.Xml;
	using System.Text.RegularExpressions;

	/// <summary>
	/// The RegExValidationStep is used to validate a data stream by evaluating one or more regular expressions against it.
	/// </summary>
	/// 
	/// <remarks>
	/// The following shows an example of the Xml representation of this test step.
	/// 
	/// <code escaped="true">
	///	<ValidationStep assemblyPath="" typeName="Microsoft.Services.BizTalkApplicationFramework.BizUnit.RegExValidationStep">
	///		<ValidationRegEx>Event Type   - Switch</ValidationRegEx>
	///		<ValidationRegEx>{1:[a-z]3</ValidationRegEx>
	///	</ValidationStep>
	///	</code>
	///	
	///	<list type="table">
	///		<listheader>
	///			<term>Tag</term>
	///			<description>Description</description>
	///		</listheader>
	///		<item>
	///			<term>ValidationRegEx</term>
	///			<description>The regualar expression to be evaluated <para>(repeating)</para></description>
	///		</item>
	///	</list>
	///	</remarks>

	public class RegExValidationStep : IValidationStep
	{
		/// <summary>
		/// IValidationStep.ExecuteValidation() implementation
		/// </summary>
		/// <param name='data'>The stream cintaining the data to be validated.</param>
		/// <param name='validatorConfig'>The Xml fragment containing the configuration for the test step</param>
		/// <param name='context'>The context for the test, this holds state that is passed beteen tests</param>
		public void ExecuteValidation(Stream data, XmlNode validatorConfig, Context context)
		{
			XmlNodeList validationNodes = validatorConfig.SelectNodes("ValidationRegEx");

			StreamReader sr = new StreamReader( data );
			string strData = sr.ReadToEnd();

			foreach (XmlNode validationNode in validationNodes)
			{
				string matchPattern = validationNode.InnerText;
				Match match = Regex.Match(strData, matchPattern);

				if (match.Success)
				{
					context.LogInfo("Regex validation succeeded for pattern \"{0}\".", matchPattern);
				}
				else
				{
					throw new Exception(String.Format("Regex validation failed for pattern \"{0}\".", matchPattern));
				}
			}
		}
	}
}
